<template>
  <view class="page">
    <view v-if="$data.info">
      <view class="top">
        <view class="basic">
          <view class="basic_img">
            <image :src="$data.info._picurl" />
          </view>
          <view class="basic_content">
            <view class="basic_content--title">
              {{ $data.info.serviceTitle }}
            </view>
            <view class="basic_content--price text-price">
              {{ $data.info.firstTotalPrice }}
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 保障 </view>
          <view class="row_right">
            <view class="flex align-center flex-warp">
              <view
                class="margin-right"
                v-for="(item, index) of $data.info.serviceSnapshot
                  .serviceTagNameArr"
                :key="index"
              >
                <up-icon
                  name="checkmark-circle"
                  color="#111111"
                  labelColor="#111111"
                  :label="item"
                  :size="18"
                  :labelSize="16"
                ></up-icon>
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 温馨提示 </view>
          <view class="row_right">
            {{ removeHtmlTags($data.info.serviceSnapshot.tips) }}
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单总价 </view>
          <view class="row_right text-price">{{ $data.info.totalPrice }}</view>
        </view>
        <view class="row">
          <view class="row_left"> 优惠 </view>
          <view class="row_right text-price">
            -{{ $data.info.couponPrice }}
          </view>
        </view>
        <!-- <view class="row" v-if="$data.info.fast">
          <view class="row_left"> 加急 </view>
          <view class="row_right text-price">
            {{ $data.info.fast }}
          </view>
        </view> -->
        <view class="row" v-if="Number($data.info.replenishPrice)">
          <view class="row_left">续时金额</view>
          <view class="row_right text-price">
            {{ $data.info.replenishPrice }}
          </view>
        </view>
      </view>
      <!-- 阿姨信息 -->
      <view class="worker" v-if="$data.info.workerDetail">
        <!-- 轨迹地图 -->
        <view class="map">
          <map
            :longitude="$data.centerPoint.longitude"
            :latitude="$data.centerPoint.latitude"
            :scale="12"
            :markers="[$data.customPoint, $data.workerPoint]"
            :polyline="$data.polyline"
          />
        </view>
        <view class="detail">
          <view class="detail_img">
            <image :src="$data.info.workerDetail._avatar" />
          </view>
          <view class="detail_content">
            <view class="detail_content--title">
              {{ $data.info.workerDetail.nickname }}
            </view>
            <view class="scoring">
              <view
                class="scoring_item"
                v-for="(icon, iconIndex) in 5"
                :key="iconIndex"
              >
                <up-icon
                  name="star-fill"
                  :color="
                    iconIndex < $data.info.workerDetail.star
                      ? BasicConfig.MainColor
                      : '#bbbbbb'
                  "
                ></up-icon>
              </view>
            </view>
            <view class="detail_content--phone">
              <view>
                {{ hidePhone($data.info.workerDetail.phone) }}
              </view>
              <view class="copy" @tap="onCall(phoneType.worker)">
                联系保洁师
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="margin-top padding-lr bg-white">
        <view class="row">
          <view class="row_left"> 服务时间 </view>
          <view class="row_right">
            <view class="flex justify-between align-center">
              <view>{{ $data.info._firstStartServicedAt }}</view>
              <view class="copy text-nowarp" @tap="onCall(phoneType.custom)">
                修改
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 服务地址 </view>
          <view class="row_right">
            {{ $data.info.addressSnapshot.locationAddress }}
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 联系人 </view>
          <view class="row_right">
            <text> {{ $data.info.addressSnapshot.name }}</text>
            <text>
              ({{ $data.info.addressSnapshot.sex == 1 ? "先生" : "女士" }})
            </text>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单编号 </view>
          <view class="row_right">
            <view class="flex justify-between align-center">
              <view>
                {{ $data.info.localNo }}
              </view>
              <view class="copy" @tap="onCopy($data.info.localNo)">复制</view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 下单时间 </view>
          <view class="row_right">
            {{ $data.info._createdAt }}
          </view>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="foot foot_box">
        <block v-if="isDown">
          <view class="btn btn_down">服务已下架</view>
        </block>
        <block v-else>
          <view class="btn btn_cancel" @tap="onComplaint"> 投诉 </view>
          <block v-if="showApply">
            <block
              v-if="
                $data.info && $data.info.dyGoodsType == goodsType.reservation
              "
            >
              <view
                class="btn btn_save"
                v-if="
                  $data.info.refundSwitch == reservaSwitch.off &&
                  $data.info.status != orderStatus.awaitReservation
                "
                @tap="onCall(phoneType.custom)"
              >
                联系客服
              </view>
              <view class="btn btn_save" v-else @tap="onReservaApply">
                申请售后
              </view>
            </block>
            <view class="btn btn_cancel" v-else @tap="onApply"> 申请售后 </view>
          </block>
          <view class="btn btn_cancel" v-else @tap="onLookApply">
            查看售后
          </view>
          <!-- <view class="btn btn_cancel" v-if="showApply" @tap="onApply">
            申请售后
          </view>
          <view class="btn btn_cancel" v-else @tap="onLookApply">
            查看售后
          </view> -->
        </block>
      </view>
    </view>
    <PopupCSPhone
      v-model:show="$data.csphoneShow"
      :title="$data.csTitle"
      :type="$data.csType"
      :phone="phone"
    />
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick, computed } from "vue";
import { onLoad, onShow, onHide, onReady, onUnload } from "@dcloudio/uni-app";
import { getOrderDetail, nowLocation } from "../../../../api/Interface/order";
import errorCode from "../../../../utils/http/errorCode";
import { isDev } from "../../../../utils/env";
import BasicConfig from "../../../../utils/config";
import {
  afterSalesApplyStatus,
  hotelOrderAfterSaleStatus,
  orderSecondStatus,
  orderStatus,
  orderStatusConfig,
  orderType,
} from "../../../../enums/order";
import { jumpPage } from "../../../../utils/route/route";
import PopupCSPhone from "../../../../components/PopupCSPhone.vue";
import { phoneType } from "../../../../enums/common";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import "dayjs/locale/zh-cn";
import { useImgSrc } from "../../../../hooks/useImg";
import { useGetUserStorage } from "../../../../hooks/useStorage";
import {
  getPointsCalculateCenter,
  hidePhone,
  removeHtmlTags,
} from "../../../../utils/utils";
import { workerStatus } from "../../../../enums/worker";
import { reservaSwitch, goodsType } from "../../../../enums/goods";
import { useJumpOrderPage } from "../../../../hooks/useOrder";
dayjs.extend(duration);
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  localNo: "",
  orderServiceId: "",
  info: null,
  csphoneShow: false,
  csTitle: "联系电话",
  csType: phoneType.custom,
  /** 用户坐标点 */
  customPoint: {
    id: 0,
    latitude: 0, // 纬度
    longitude: 0, // 经度
    iconPath: "",
    width: "60rpx",
    height: "60rpx",
  },
  /** 保洁师起始坐标点 */
  workerPoint: {
    id: 1,
    latitude: 0, // 纬度
    longitude: 0, // 经度
    iconPath: "",
    width: "60rpx",
    height: "60rpx",
  },
  centerPoint: {
    latitude: 0, // 纬度
    longitude: 0, // 经度
  },
  // 路线
  polyline: [
    {
      points: [],
    },
  ],
  timer: null,
  pageIndex: "",
});
/**
 * 计算属性用于确定是否显示申请按钮
 */
const showApply = computed(() => {
  // isHasRefund 1.已申请过售后 0.未申请售后
  return (
    $data.info &&
    $data.info.firstAfterSaleStatus == hotelOrderAfterSaleStatus.normal &&
    $data.info.secondStatus == orderSecondStatus.cancel &&
    $data.info.isHasRefund == afterSalesApplyStatus.not
  );
});
const onCopy = (text) => {
  uni.setClipboardData({
    data: text.toString(),
    success: (result) => {
      BasicConfig.toast("复制成功");
    },
    fail: (error) => {
      console.log("复制失败", error);
      BasicConfig.toast("复制失败!");
    },
  });
};
const init = async () => {
  await getOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      useJumpOrderPage(res.data);
      if ($data.info) {
        setTitle();
        $data.info._picurl = useImgSrc($data.info.picurl);
        const { firstStartServicedAt, createdAt } = res.data;
        $data.info._firstStartServicedAt = dayjs(firstStartServicedAt)
          .locale("zh-cn")
          .format("YYYY-MM-DD dddd HH:mm");
        $data.info._createdAt = dayjs(createdAt)
          .locale("zh-cn")
          .format("YYYY-MM-DD dddd HH:mm");
        if ($data.info.workerDetail) {
          $data.info.workerDetail._avatar = useImgSrc(
            $data.info.workerDetail.avatar
          );
        }
      }
    }
  });
  getPoint();
};
const getPoint = async () => {
  if (!$data.info) return;
  const {
    workerDetail = {},
    addressSnapshot = {},
    orderServiceWorker = {},
  } = $data.info;
  $data.customPoint.latitude = Number(addressSnapshot.lat);
  $data.customPoint.longitude = Number(addressSnapshot.lng);
  const userInfo = useGetUserStorage();
  $data.customPoint.iconPath = useImgSrc(userInfo?.avatar);
  $data.workerPoint.latitude = Number(workerDetail.takeLat);
  $data.workerPoint.longitude = Number(workerDetail.takeLng);
  $data.workerPoint.iconPath = useImgSrc(workerDetail.avatar);
  console.log(
    "用户坐标",
    uni.$u.deepClone($data.customPoint),
    uni.$u.deepClone($data.info)
  );
  console.log("保洁师初始坐标", uni.$u.deepClone($data.workerPoint));
  formatPoint();
  $data.timer = setInterval(async () => {
    console.log("坐标请求参数", {
      workerId: workerDetail.workerId,
      departAt: orderServiceWorker.departAt,
      pageIndex: $data.pageIndex,
    });
    await nowLocation({
      workerId: workerDetail.workerId,
      departAt: orderServiceWorker.departAt,
      pageIndex: $data.pageIndex,
    }).then((res) => {
      if (res.code === errorCode.success) {
        const { data } = res;
        // const points = data.track ?? [];
        // $data.polyline[0].points = points.map((m) => {
        //   return {
        //     latitude: m.lat, // 纬度
        //     longitude: m.lng, // 经度
        //   };
        // });
        // console.log("$data.polyline", uni.$u.deepClone($data.polyline))
        // const point = data.track?.[0] ?? [];
        $data.workerPoint.latitude = Number(data.lat);
        $data.workerPoint.longitude = Number(data.lng);
        $data.pageIndex = data.pageIndex;
        formatPoint();
        console.log("保洁师坐标~", uni.$u.deepClone($data.workerPoint), data);
        // $data.workerPoint.iconPath = useImgSrc(workerDetail.avatar);
      }
    });
  }, 30000);
};
const formatPoint = () => {
  // 设置中心点
  const list = getPointsCalculateCenter([
    [$data.customPoint.latitude, $data.customPoint.longitude],
    [$data.workerPoint.latitude, $data.workerPoint.longitude],
  ]);
  $data.centerPoint.latitude = list[0];
  $data.centerPoint.longitude = list[1];
};
const setTitle = () => {
  uni.setNavigationBarTitle({
    title: orderStatusConfig[$data.info.firstStatus]?.label ?? "",
  });
};
const onCall = (type) => {
  $data.csphoneShow = true;
  $data.csType = type;
  if (type == phoneType.worker) {
    $data.csTitle = "保洁师电话";
  } else if (type === phoneType.custom) {
    $data.csTitle = "官方客服电话";
  }
};
const phone = computed(() => {
  if ($data.info && $data.info.workerDetail && $data.info.workerDetail.phone) {
    return $data.info.workerDetail.phone;
  }
  return "";
});
/** 是否下架 domesticServiceStatus 0.已下架 1.已上架 */
const isDown = computed(() => {
  const { domesticServiceStatus } = $data.info;
  return domesticServiceStatus == 0;
});
const onApply = () => {
  const { secondStatus, orderServiceWorker = null } = $data.info;
  const canApply = !orderServiceWorker || [
    workerStatus.cancel,
    workerStatus.await,
    workerStatus.awaitReservation,
    workerStatus.awaitCome,
  ];
  // 没有二次上门 可退款
  if (secondStatus == orderSecondStatus.cancel && canApply) {
    jumpPage({
      to: "/package-service/pages/order/afterSales/apply",
      query: {
        localNo: $data.localNo,
        orderServiceId: $data.orderServiceId,
      },
    });
  }
  // 有二次上门 只能拨打电话
  else {
    onCall(phoneType.custom);
  }
};
const onLookApply = () => {
  jumpPage({
    to: "/package-service/pages/order/afterSales/apply",
    query: {
      localNo: $data.localNo,
      orderServiceId: $data.orderServiceId,
    },
  });
};
// 预约品跳转售后
const onReservaApply = () => {
  // // orderStatus.awaitReservation != $data.info.status
  // // clearHandle();
  jumpPage({
    to: "/package-service/pages/order/afterSales/apply",
    query: {
      localNo: $data.localNo,
      orderServiceId: $data.orderServiceId,
    },
  });
  // // 待预约的预约品
  // if (orderStatus.awaitReservation == $data.info.status) {
  //   jumpPage({
  //     to: "/package-service/pages/order/afterSales/apply",
  //     query: {
  //       localNo: $data.localNo,
  //       orderServiceId: $data.orderServiceId,
  //     },
  //   });
  // } else {
  //   jumpPage({
  //     to: "/package-service/pages/order/afterSalesReserva/apply",
  //     query: {
  //       localNo: $data.localNo,
  //       orderServiceId: $data.orderServiceId,
  //     },
  //   });
  // }
};
const onComplaint = () => {
  jumpPage({
    to: "/package-service/pages/complain",
    query: {
      orderServiceId: $data.orderServiceId,
      domesticServiceId: $data.info.serviceSnapshot.domesticServiceId,
      localNo: $data.localNo,
      orderType: orderType.service,
    },
  });
};
const clearHandle = () => {
  clearInterval($data.timer);
  $data.timer = null;
};
onLoad((options) => {
  $data.localNo = options.localNo;
  $data.orderServiceId = options.orderServiceId;
  init();
});
onUnload(() => {
  clearHandle();
});
onReady(() => {});
</script>

<style lang="scss" scoped>
@import "../../../static/style/order/detail/common.scss";
.map {
  width: 100%;
  height: 30vh;
  map {
    width: 100%;
    height: 100%;
    image {
      border-radius: 100% !important;
    }
    img {
      border-radius: 100% !important;
    }
  }
  image {
    border-radius: 100% !important;
  }
  img {
    border-radius: 100% !important;
  }
}
</style>
